package com.atguigu.sso.server.Controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

@Controller
public class LoginController {

    @Autowired
    StringRedisTemplate redisTemplate;


    @GetMapping("/login.html")
    public String login(@RequestParam("url") String url, Model model,
                        @CookieValue(value = "sso_cookie",required = false) String cookieString ){


        if(!StringUtils.isEmpty(cookieString)){
            return "redirect:"+url+"?sso_token="+cookieString;
        }
        model.addAttribute("url",url);
        return "login";
    }


    @PostMapping("/doLogin")
    public String doLogin(@RequestParam("username") String username,
                          @RequestParam("password") String password,
                          @RequestParam("url") String url,
                          HttpServletResponse response){

        // 假设登录成功  返回一个Uuid  把中间的 横线替换掉
        String uuid = UUID.randomUUID().toString().replace("-","");
        if(!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)){
            //登录成功 在当前服务域名留下标志
            Cookie sso_cookie = new Cookie("sso_cookie", uuid);
            response.addCookie(sso_cookie);


            redisTemplate.opsForValue().set("sso:user",username);
            return "redirect:"+url+"?sso_token="+uuid;
       }

        return "login";
    }

}
